<template>
  <div>
    <h3>批量 curd上传图片</h3>
    <!-- 大概思路就是，只需要el-upload去帮我们维护fileList，但是不需要它帮我们上传。点击提交按钮的时候才上传 -->
    <el-upload class="avatar-uploader" action="" :file-list="fileList" :auto-upload="false" :on-change="handleChange" :on-remove="handleRemove" :show-file-list="false">
      <div v-if="fileList.length > 0" class="fileList">
        <img v-for="(file, index) in fileList" :key="index" :src="file.url" class="avatar">
      </div>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-button @click="submit">提交</el-button>
  </div>
</template>

<script>
import fileUtil from "@/common/com.wyl.util/fileUtil.js"
import imgList from "@/common/apiData/img.json"

export default {
  created () {
    // 获取图片接口，并将图片转换成file，这样上传文件的时候才不会丢失
    for (let img of imgList) {
      img.raw = fileUtil.base64toFile(img.url);
    }
    this.fileList = imgList
  },
  data () {
    return {
      fileList: [
        // {name: "文件名称", url: "文件url", raw: "File对象"}
      ]
    }
  },
  methods: {
    async handleChange (file, fileList) {
      for (let _file of fileList) {
        _file.url = await fileUtil.fileToBase64(_file.raw);
      }
      this.fileList = fileList;
    },
    handleRemove () {

    },
    submit () {
      let formData = new FormData();
      for (let file of this.fileList) {
        formData.append('file', file.raw)
      }
      this.$api.system.user.uploadFiles(formData).then(res => {
        console.log(res)
      }).catch(err => {
        console.error(err)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }

  .fileList {
    display: flex;
    //   缩略图
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>